/**
 * @param {string} p
 * @return {number}
 */
export var findSubstringInWraproundString = function (p) {
  if (p.length < 2) return p.length
  const memo = new Array(26).fill(0)
  let ans = 1
  let startIdx = 0
  memo[p[0].charCodeAt() - 'a'.charCodeAt()] = 1
  for (let i = 1; i < p.length; i++) {
    const cur = p[i]
    const pre = p[i - 1]
    if ((cur.charCodeAt() - pre.charCodeAt() + 26) % 26 !== 1) startIdx = i
    ans += getNewSubStrsLen(p, startIdx, i, memo)
  }
  return ans
}

function getNewSubStrsLen(p, s, e, memo) {
  const len = e - s + 1
  const newLen = len - memo[p[e].charCodeAt() - 'a'.charCodeAt()]
  if (newLen > 0) {
    memo[p[e].charCodeAt() - 'a'.charCodeAt()] = len
    return newLen
  }
  return 0
}

/**
 * 简化上边代码
 * @param {string} p
 * @return {number}
 */
export var findSubstringInWraproundString2 = function (p) {
  const memo = new Array(26).fill(0)
  let [ans, startIdx] = [0, 0]
  for (let i = 0; i < p.length; i++) {
    if (i > 0 && (p[i].charCodeAt() - p[i - 1].charCodeAt() + 26) % 26 !== 1) startIdx = i
    const len = i - startIdx + 1
    if (len > memo[p[i].charCodeAt() - 'a'.charCodeAt()]) {
      ans += len - memo[p[i].charCodeAt() - 'a'.charCodeAt()]
      memo[p[i].charCodeAt() - 'a'.charCodeAt()] = len
    }
  }
  return ans
}
